package filescript;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

import actions.Action;

import filters.FileFilter;

public class SectionManager {
	
	private ArrayList<File> _filteredFiles;
	
	public SectionManager (ArrayList<File> files) {
		_filteredFiles = new ArrayList<File> (files);
	}
	
	public void runSection (Section sec, ArrayList<File> files) throws IOException {
		
		runFilters(sec.getFilters());
		printComments(sec.getComments());
		runActions(sec.getActions(), sec.getOrder(), files);
	}
	
	
	private void runFilters(ArrayList<FileFilter> filters){
		ArrayList<File> notPassed = new ArrayList<File>(_filteredFiles);
		for (FileFilter filter : filters){
			if (filter == null){
				cleanUp(notPassed);
				notPassed = new ArrayList<File>(_filteredFiles);
			}
			else {
				for (File f : notPassed) {
					if (filter.accept(f))
						notPassed.remove(f);
				}
			}
		}
		
	}
	
	private void cleanUp(ArrayList<File> toRemove){
		for(File f : toRemove)
			_filteredFiles.remove(f);
	}
	
	private void printComments(ArrayList<String> comments){
		for (String s : comments)
			System.out.println(s);
	}
	
	private void runActions(ArrayList<Action> actions, Comparator<File> comp,
						    ArrayList<File> orgFiles) throws IOException{
		TreeSet<File> files = new TreeSet<File>(comp);
		files.addAll(_filteredFiles);
		Iterator<File> nextFile = files.iterator();
		File currFile;
		while ( nextFile.hasNext() ){
			currFile = nextFile.next();
			for ( Action ac : actions ){
				ac.doAction(currFile, orgFiles);
			}
		}
			
	}


}
